<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { layers, specieNameList, speciesDistribute } from '@/utils/api.js'
import * as mars3d from "mars3d";
import "mars3d/dist/mars3d.css";
//引入cesium基础库
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css";
import * as Cesium from "mars3d-cesium";
import "mars3d-heatmap";

import point from '@/assets/images/point.png'
import layer from '@/assets/images/layer.png'
import full from '@/assets/images/full.png'

// 地图变量
let areaId = '';
const isbl = ref(false);
const ispg = ref(false);
const blarr = ref([]);
const blList = ref([]);
const pgarr = ref([]);
const pgList = ref([]);
const type = ref('动物');
const keywords = ref('');
const specie = ref([]);
let maptd = null;
let pointLayer = null;
let yjlayer = null;
let patrolLayer = null;
let heatLayer = null;
let devpoint = {};
let layerObj = {};
const PersonModel = '//data.mars3d.cn/gltf/mars/man/walk.gltf'
// 初始化地图
const maptdInit = () => {
    var mapOptions = {
        scene: {
            //默认视角参数
            center: { "lat": 40.029431, "lng": 116.805358, "alt": 6957.2, "heading": 356, "pitch": -33.8 },
            shadows: false, //是否启用日照阴影
            removeDblClick: true, //是否移除Cesium默认的双击事件

            //以下是Cesium.Viewer所支持的options【控件相关的写在另外的control属性中】
            sceneMode: 3, //3等价于Cesium.SceneMode.SCENE3D,

            //以下是Cesium.Scene对象相关参数
            showSun: true, //是否显示太阳
            showMoon: true, //是否显示月亮
            showSkyBox: true, //是否显示天空盒
            showSkyAtmosphere: true, //是否显示地球大气层外光圈
            fog: true, //是否启用雾化效果
            fxaa: true, //是否启用抗锯齿

            //以下是Cesium.Globe对象相关参数
            globe: {
                depthTestAgainstTerrain: false, //是否启用深度监测
                baseColor: '#546a53', //地球默认背景色
                showGroundAtmosphere: true, //是否在地球上绘制的地面大气
                enableLighting: false //是否显示昼夜区域
            },
            //以下是Cesium.ScreenSpaceCameraController对象相关参数
            cameraController: {
                zoomFactor: 3.0, //鼠标滚轮放大的步长参数
                minimumZoomDistance: 1, //地球放大的最小值（以米为单位）
                maximumZoomDistance: 50000000, //地球缩小的最大值（以米为单位）
                enableRotate: true, //2D和3D视图下，是否允许用户旋转相机
                enableTranslate: true, //2D和哥伦布视图下，是否允许用户平移地图
                enableTilt: true, // 3D和哥伦布视图下，是否允许用户倾斜相机
                enableZoom: true, // 是否允许 用户放大和缩小视图
                enableCollisionDetection: true //是否允许 地形相机的碰撞检测
            }
        },
        control: {
            baseLayerPicker: false, //basemaps底图切换按钮
            homeButton: false, //视角复位按钮
            sceneModePicker: false, //二三维切换按钮
            navigationHelpButton: false, //帮助按钮
            fullscreenButton: false, //全屏按钮  
        },
        terrain: {
            url: 'http://data.mars3d.cn/terrain',
            show: true
        },
        basemaps: [{
            name: '天地图卫星',
            icon: 'img/basemaps/tdt_img.jpg',
            type: 'tdt',
            layer: 'img_d',
            key: ['f24cec70606332017dcd39a4fb60dd11'],
            show: true
        }],
    };
    maptd = new mars3d.Map("mars3dContainer", mapOptions);
    maptd.scene.globe.depthTestAgainstTerrain = true;
    // fly();
    // 创建点位图层
    pointLayer = new mars3d.layer.GraphicLayer({});
    maptd.addLayer(pointLayer);
    // 预警图层
    yjlayer = new mars3d.layer.GraphicLayer();
    maptd.addLayer(yjlayer);
    // 创建巡护图层
    patrolLayer = new mars3d.layer.GraphicLayer({ zIndex: 15, });
    maptd.addLayer(patrolLayer);


};



// 创建wms
const addwms = (id, data) => {
    if (layerObj.hasOwnProperty(id)) {
        removelayers(id);
    } else {
        layerObj[id] = new mars3d.layer.WmsLayer({
            url: data.layerUrl,
            layers: data.layerName,
            parameters: {
                transparent: true,
                format: "image/png",
                cql_filter: data.cql,
                STYLES: data.styleId
            },
            // opacity: 0.5
        })
        if (maptd != null) {
            maptd.addLayer(layerObj[id]);
        }
    }
}

// 删除wms
const removelayers = (id) => {
    maptd.removeLayer(layerObj[id], true)
    delete layerObj[id]
}

// 设备点位
const adddevices = (id, data, icon) => {
    //设备点位图层
    devpoint[id] = new mars3d.layer.GraphicLayer({});
    maptd.addLayer(devpoint[id]);
    for (let i = 0; i < data.length; i++) {
        let p = data[i];
        const position = [p.lon, p.lat, 0];
        let po = new mars3d.graphic.BillboardEntity({
            position: position,
            style: {
                image: icon,
                scale: .5,
                scaleByDistance: true,
                clampToGround: true,
                visibleDepth: true,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                // scaleByDistance: new Cesium.NearFarScalar(1000, 1, 5000, 0.5),
            },
            attr: {}
        })
        devpoint[id].addGraphic(po)
    }
}

// 删除设备点位
const deldevices = (id) => {
    maptd.removeLayer(devpoint[id], true);
    delete devpoint[id];
}

const getlayers = async () => {
    let res = await layers(areaId)
    blList.value = res.data.point;
    pgList.value = res.data.polygon;
}

const getspecieNameList = async () => {
    let res = await specieNameList(areaId, type.value, '')
    if (res.code == '200') {
        specie.value = res.data;
        keywords.value = res.data[0].name;
        console.log(keywords.value);
        getspeciesDistribute();
    }
}

const generateRandomNumber = () => {
    return Math.floor(Math.random() * 9901) + 100; // 10000 - 100 + 1 = 9901
}

const getspeciesDistribute = async () => {
    let res = await speciesDistribute(areaId, type.value, keywords.value)
    if (res.code == '200') {
        let arrPoints = [];
        res.data.forEach(e => {
            arrPoints.push({ lng: e.lon, lat: e.lat, value: generateRandomNumber() })
        });
        drawHeat(arrPoints)
    }
}

// 添加热力图
const drawHeat = (arrPoints) => {
    if (heatLayer != null) {
        maptd.removeLayer(heatLayer, true)
        heatLayer = null;
    }
    heatLayer = new mars3d.layer.HeatLayer({
        positions: arrPoints,
        max: 20000,
        heatStyle: {
            radius: 20,
            minOpacity: 0,
            maxOpacity: 0.4,
            blur: 0.3,
            gradient: {
                0: "#e9ec36",
                0.25: "#ffdd2f",
                0.5: "#fa6c20",
                0.75: "#fe4a33",
                1: "#ff0000"
            }
        },
        // 以下为矩形矢量对象的样式参数
        style: {
            opacity: 1.0,
            clampToGround: true,
        },
        flyTo: true
    })
    if (maptd != null) {
        console.log(22);
        maptd.addLayer(heatLayer)
    }

}

const destroyMap = () => {
    if (!maptd) {
        return
    }
    maptd.destroy()
    maptd = null
}

onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');
    maptdInit();
    getlayers();
    getspecieNameList();
});


onUnmounted(() => {
    destroyMap()
})

</script>
<template>
    <div id="mars3dContainer">
        <div class="control">
            <div class="ly">
                <img :src="point" alt="" @click.stop="isbl = !isbl">
                <div class='z_1' v-show="isbl">
                    <div class='lx'>
                    </div>
                    <div class='fx'>
                        <el-checkbox-group v-model="blarr">
                            <el-checkbox v-for='bl in blList' :key='bl.name' :label="bl.name" @change='addwms(bl.id, bl)'>
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </div>
            </div>
            <div class="ly">
                <img :src="layer" alt="" @click.stop="ispg = !ispg">
                <div class='z_1' v-show="ispg">
                    <div class='lx'>
                    </div>
                    <div class='fx'>
                        <el-checkbox-group v-model="pgarr">
                            <el-checkbox v-for='pg in pgList' :key='pg.name' :label="pg.name" @change='addwms(pg.id, pg)'>
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </div>
            </div>
            <el-select v-model="type" placeholder="Select" style="width: 80px">
                <el-option label="动物" value="1" />
                <el-option label="植物" value="2" />
            </el-select>
            <el-select v-model="keywords" placeholder="Select" filterable @change="getspeciesDistribute()"
                style="width: 150px">
                <el-option v-for="(i, index) in specie" :label="i.name + '(' + i.cishu + ')次'" :value="i.name" />
            </el-select>
        </div>
    </div>
</template>
<style scoped>
#mars3dContainer {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

.control {
    width: 5rem;
    display: flex;
    position: absolute;
    top: 1.9rem;
    left: 5.3rem;
    display: flex;
    z-index: 1;
}

.ly {
    width: 0.5rem;
    height: 0.42rem;
    margin-right: 0.16rem;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    background: rgba(4, 43, 52, 0.9);
    cursor: pointer;
}

.ly img {
    width: .24rem;
    height: 0.24rem;
}


.z_1 {
    position: absolute;
    top: 0.42rem;
    left: 0;
    z-index: 2;
}

.lx {
    width: 12px;
    height: 12px;
    margin-left: 9px;
    background-color: rgba(4, 43, 52, 0.9);
    transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    /* IE 9 */
    -moz-transform: rotate(45deg);
    /* Firefox */
    -webkit-transform: rotate(45deg);
    /* Safari 和 Chrome */
    -o-transform: rotate(45deg);
    /* Opera */
}

.fx {
    padding: .2rem .2rem 0 .2rem;
    position: absolute;
    top: 6px;
    left: 0;
    border-radius: 4px;
    box-shadow: 0 3px 24px 0 rgba(0, 0, 0, 0.12);
    background-color: rgba(4, 43, 52, 0.9);
    overflow: hidden;
}


.zdy {
    width: 4.2rem;
    height: 0.4rem;
    display: flex;
    background-color: #fff;
    border-radius: 4px;
}
</style>

<style>
.el-checkbox {
    color: #fff !important;
}
</style>